// 工具函数

export class ToolsManager {
    constructor() {
        this.imageViewer = null;
        this.activeTool = null;
        this.measurements = [];
        this.isDrawing = false;
        this.currentMeasurement = null;
        this.canvas = null;
        this.overlayCanvas = null;
        this.overlayContext = null;
    }

    initialize(imageViewer) {
        this.imageViewer = imageViewer;
        this.canvas = imageViewer.canvas;
        this.createOverlayCanvas();
        this.setupEventListeners();
    }

    createOverlayCanvas() {
        if (!this.canvas) return;

        // 创建覆盖层canvas用于绘制测量工具
        this.overlayCanvas = document.createElement('canvas');
        this.overlayCanvas.style.position = 'absolute';
        this.overlayCanvas.style.top = '0';
        this.overlayCanvas.style.left = '0';
        this.overlayCanvas.style.pointerEvents = 'none';
        this.overlayCanvas.style.zIndex = '10';
        
        // 插入到主canvas之后
        this.canvas.parentNode.insertBefore(this.overlayCanvas, this.canvas.nextSibling);
        
        this.overlayContext = this.overlayCanvas.getContext('2d');
        this.resizeOverlayCanvas();
        
        // 监听窗口大小变化
        window.addEventListener('resize', () => this.resizeOverlayCanvas());
    }

    resizeOverlayCanvas() {
        if (!this.overlayCanvas || !this.canvas) return;
        
        this.overlayCanvas.width = this.canvas.width;
        this.overlayCanvas.height = this.canvas.height;
        this.overlayCanvas.style.width = this.canvas.style.width;
        this.overlayCanvas.style.height = this.canvas.style.height;
        
        // 重新绘制测量结果
        this.redrawMeasurements();
    }

    setupEventListeners() {
        if (!this.canvas) return;

        // 重写图像查看器的鼠标事件以支持测量工具
        this.canvas.addEventListener('mousedown', (e) => this.handleMouseDown(e), true);
        this.canvas.addEventListener('mousemove', (e) => this.handleMouseMove(e), true);
        this.canvas.addEventListener('mouseup', (e) => this.handleMouseUp(e), true);
        this.canvas.addEventListener('dblclick', (e) => this.handleDoubleClick(e), true);
    }

    activateTool(toolName) {
        // 清除之前的工具状态
        this.deactivateCurrentTool();
        
        this.activeTool = toolName;
        this.canvas.style.cursor = 'crosshair';
        
        // 更新UI按钮状态
        this.updateToolButtons(toolName);
    }

    deactivateCurrentTool() {
        this.activeTool = null;
        this.isDrawing = false;
        this.currentMeasurement = null;
        this.canvas.style.cursor = 'crosshair';
        
        // 更新UI按钮状态
        this.updateToolButtons(null);
    }

    updateToolButtons(activeTool) {
        // 移除所有按钮的激活状态
        document.querySelectorAll('.measurement-tools .tool-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        
        // 激活当前工具按钮
        if (activeTool) {
            const toolButton = document.getElementById(`${activeTool}MeasureBtn`);
            if (toolButton) {
                toolButton.classList.add('active');
            }
        }
    }

    handleMouseDown(event) {
        if (!this.activeTool) {
            // 如果没有激活的测量工具，让图像查看器处理事件
            return;
        }

        event.stopPropagation();
        event.preventDefault();

        const mousePos = this.getMousePos(event);
        
        switch (this.activeTool) {
            case 'length':
                this.startLengthMeasurement(mousePos);
                break;
            case 'angle':
                this.startAngleMeasurement(mousePos);
                break;
            case 'area':
                this.startAreaMeasurement(mousePos);
                break;
        }
    }

    handleMouseMove(event) {
        if (!this.activeTool || !this.isDrawing) {
            return;
        }

        event.stopPropagation();
        event.preventDefault();

        const mousePos = this.getMousePos(event);
        
        switch (this.activeTool) {
            case 'length':
                this.updateLengthMeasurement(mousePos);
                break;
            case 'angle':
                this.updateAngleMeasurement(mousePos);
                break;
            case 'area':
                this.updateAreaMeasurement(mousePos);
                break;
        }
    }

    handleMouseUp(event) {
        if (!this.activeTool || !this.isDrawing) {
            return;
        }

        event.stopPropagation();
        event.preventDefault();

        const mousePos = this.getMousePos(event);
        
        switch (this.activeTool) {
            case 'length':
                this.finishLengthMeasurement(mousePos);
                break;
            case 'angle':
                this.finishAngleMeasurement(mousePos);
                break;
            case 'area':
                this.finishAreaMeasurement(mousePos);
                break;
        }
    }

    handleDoubleClick(event) {
        if (!this.activeTool) return;

        event.stopPropagation();
        event.preventDefault();

        if (this.activeTool === 'area' && this.currentMeasurement) {
            // 完成区域测量
            this.completeAreaMeasurement();
        }
    }

    // 长度测量
    startLengthMeasurement(startPos) {
        this.isDrawing = true;
        this.currentMeasurement = {
            type: 'length',
            points: [startPos, startPos],
            id: Date.now()
        };
    }

    updateLengthMeasurement(currentPos) {
        if (!this.currentMeasurement) return;
        
        this.currentMeasurement.points[1] = currentPos;
        this.redrawMeasurements();
    }

    finishLengthMeasurement(endPos) {
        if (!this.currentMeasurement) return;
        
        this.currentMeasurement.points[1] = endPos;
        this.currentMeasurement.length = this.calculateLength(
            this.currentMeasurement.points[0],
            this.currentMeasurement.points[1]
        );
        
        this.measurements.push(this.currentMeasurement);
        this.currentMeasurement = null;
        this.isDrawing = false;
        this.redrawMeasurements();
    }

    // 角度测量
    startAngleMeasurement(startPos) {
        if (!this.currentMeasurement) {
            // 开始新的角度测量
            this.isDrawing = true;
            this.currentMeasurement = {
                type: 'angle',
                points: [startPos],
                id: Date.now()
            };
        } else if (this.currentMeasurement.points.length === 1) {
            // 添加第二个点
            this.currentMeasurement.points.push(startPos);
        } else if (this.currentMeasurement.points.length === 2) {
            // 添加第三个点并完成测量
            this.currentMeasurement.points.push(startPos);
            this.currentMeasurement.angle = this.calculateAngle(
                this.currentMeasurement.points[0],
                this.currentMeasurement.points[1],
                this.currentMeasurement.points[2]
            );
            this.measurements.push(this.currentMeasurement);
            this.currentMeasurement = null;
            this.isDrawing = false;
        }
        this.redrawMeasurements();
    }

    updateAngleMeasurement(currentPos) {
        if (!this.currentMeasurement) return;
        
        if (this.currentMeasurement.points.length === 1) {
            // 更新第二个点
            if (this.currentMeasurement.points.length === 1) {
                this.currentMeasurement.points[1] = currentPos;
            }
        } else if (this.currentMeasurement.points.length === 2) {
            // 更新第三个点
            this.currentMeasurement.points[2] = currentPos;
        }
        
        this.redrawMeasurements();
    }

    finishAngleMeasurement(endPos) {
        // 角度测量通过点击完成，不需要在mouseup中处理
    }

    // 区域测量
    startAreaMeasurement(startPos) {
        if (!this.currentMeasurement) {
            this.isDrawing = true;
            this.currentMeasurement = {
                type: 'area',
                points: [startPos],
                id: Date.now()
            };
        } else {
            // 添加新的点
            this.currentMeasurement.points.push(startPos);
        }
        this.redrawMeasurements();
    }

    updateAreaMeasurement(currentPos) {
        if (!this.currentMeasurement || this.currentMeasurement.points.length === 0) return;
        
        // 更新最后一个点的位置（用于实时预览）
        this.currentMeasurement.previewPoint = currentPos;
        this.redrawMeasurements();
    }

    finishAreaMeasurement(endPos) {
        // 区域测量通过双击完成，不需要在mouseup中处理
    }

    completeAreaMeasurement() {
        if (!this.currentMeasurement || this.currentMeasurement.points.length < 3) return;
        
        this.currentMeasurement.area = this.calculateArea(this.currentMeasurement.points);
        delete this.currentMeasurement.previewPoint;
        this.measurements.push(this.currentMeasurement);
        this.currentMeasurement = null;
        this.isDrawing = false;
        this.redrawMeasurements();
    }

    // 计算函数
    calculateLength(point1, point2) {
        const dx = point2.x - point1.x;
        const dy = point2.y - point1.y;
        const pixelDistance = Math.sqrt(dx * dx + dy * dy);
        
        // 转换为实际距离（需要像素间距信息）
        const pixelSpacing = this.getPixelSpacing();
        const realDistance = pixelDistance * pixelSpacing;
        
        return {
            pixels: pixelDistance,
            mm: realDistance,
            formatted: `${realDistance.toFixed(2)} mm`
        };
    }

    calculateAngle(point1, point2, point3) {
        // 计算三点之间的角度
        const vector1 = { x: point1.x - point2.x, y: point1.y - point2.y };
        const vector2 = { x: point3.x - point2.x, y: point3.y - point2.y };
        
        const dot = vector1.x * vector2.x + vector1.y * vector2.y;
        const mag1 = Math.sqrt(vector1.x * vector1.x + vector1.y * vector1.y);
        const mag2 = Math.sqrt(vector2.x * vector2.x + vector2.y * vector2.y);
        
        const angle = Math.acos(dot / (mag1 * mag2)) * (180 / Math.PI);
        
        return {
            degrees: angle,
            formatted: `${angle.toFixed(1)}°`
        };
    }

    calculateArea(points) {
        // 使用鞋带公式计算多边形面积
        let area = 0;
        const n = points.length;
        
        for (let i = 0; i < n; i++) {
            const j = (i + 1) % n;
            area += points[i].x * points[j].y;
            area -= points[j].x * points[i].y;
        }
        
        const pixelArea = Math.abs(area) / 2;
        
        // 转换为实际面积
        const pixelSpacing = this.getPixelSpacing();
        const realArea = pixelArea * pixelSpacing * pixelSpacing;
        
        return {
            pixels: pixelArea,
            mm2: realArea,
            formatted: `${realArea.toFixed(2)} mm²`
        };
    }

    getPixelSpacing() {
        // 获取像素间距，默认为1mm
        if (this.imageViewer && this.imageViewer.currentImageData && this.imageViewer.currentImageData.pixelSpacing) {
            return this.imageViewer.currentImageData.pixelSpacing[0];
        }
        return 1.0;
    }

    // 绘制函数
    redrawMeasurements() {
        if (!this.overlayContext) return;
        
        // 清空覆盖层
        this.overlayContext.clearRect(0, 0, this.overlayCanvas.width, this.overlayCanvas.height);
        
        // 绘制所有已完成的测量
        this.measurements.forEach(measurement => {
            this.drawMeasurement(measurement);
        });
        
        // 绘制当前正在进行的测量
        if (this.currentMeasurement) {
            this.drawMeasurement(this.currentMeasurement, true);
        }
    }

    drawMeasurement(measurement, isActive = false) {
        const ctx = this.overlayContext;
        const color = isActive ? '#ff6b6b' : '#4ecdc4';
        const lineWidth = 2;
        
        ctx.strokeStyle = color;
        ctx.fillStyle = color;
        ctx.lineWidth = lineWidth;
        ctx.font = '12px Arial';
        
        switch (measurement.type) {
            case 'length':
                this.drawLengthMeasurement(ctx, measurement, color);
                break;
            case 'angle':
                this.drawAngleMeasurement(ctx, measurement, color);
                break;
            case 'area':
                this.drawAreaMeasurement(ctx, measurement, color, isActive);
                break;
        }
    }

    drawLengthMeasurement(ctx, measurement, color) {
        const [point1, point2] = measurement.points;
        
        // 绘制线段
        ctx.beginPath();
        ctx.moveTo(point1.x, point1.y);
        ctx.lineTo(point2.x, point2.y);
        ctx.stroke();
        
        // 绘制端点
        this.drawPoint(ctx, point1, color);
        this.drawPoint(ctx, point2, color);
        
        // 绘制长度标签
        if (measurement.length) {
            const midX = (point1.x + point2.x) / 2;
            const midY = (point1.y + point2.y) / 2;
            this.drawLabel(ctx, measurement.length.formatted, midX, midY, color);
        }
    }

    drawAngleMeasurement(ctx, measurement, color) {
        const points = measurement.points;
        
        if (points.length >= 2) {
            // 绘制第一条线
            ctx.beginPath();
            ctx.moveTo(points[0].x, points[0].y);
            ctx.lineTo(points[1].x, points[1].y);
            ctx.stroke();
            
            if (points.length >= 3) {
                // 绘制第二条线
                ctx.beginPath();
                ctx.moveTo(points[1].x, points[1].y);
                ctx.lineTo(points[2].x, points[2].y);
                ctx.stroke();
                
                // 绘制角度弧
                this.drawAngleArc(ctx, points[0], points[1], points[2], color);
                
                // 绘制角度标签
                if (measurement.angle) {
                    this.drawLabel(ctx, measurement.angle.formatted, points[1].x + 20, points[1].y - 10, color);
                }
            }
        }
        
        // 绘制所有点
        points.forEach(point => this.drawPoint(ctx, point, color));
    }

    drawAreaMeasurement(ctx, measurement, color, isActive) {
        const points = measurement.points;
        
        if (points.length < 2) return;
        
        // 绘制多边形
        ctx.beginPath();
        ctx.moveTo(points[0].x, points[0].y);
        
        for (let i = 1; i < points.length; i++) {
            ctx.lineTo(points[i].x, points[i].y);
        }
        
        // 如果是活动测量且有预览点，连接到预览点
        if (isActive && measurement.previewPoint) {
            ctx.lineTo(measurement.previewPoint.x, measurement.previewPoint.y);
        }
        
        // 如果不是活动测量，闭合多边形
        if (!isActive) {
            ctx.closePath();
            ctx.globalAlpha = 0.3;
            ctx.fill();
            ctx.globalAlpha = 1;
        }
        
        ctx.stroke();
        
        // 绘制所有点
        points.forEach(point => this.drawPoint(ctx, point, color));
        
        // 绘制面积标签
        if (measurement.area && points.length > 2) {
            const centroid = this.calculateCentroid(points);
            this.drawLabel(ctx, measurement.area.formatted, centroid.x, centroid.y, color);
        }
    }

    drawPoint(ctx, point, color) {
        ctx.fillStyle = color;
        ctx.beginPath();
        ctx.arc(point.x, point.y, 3, 0, 2 * Math.PI);
        ctx.fill();
    }

    drawLabel(ctx, text, x, y, color) {
        ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
        ctx.fillRect(x - 2, y - 14, ctx.measureText(text).width + 4, 16);
        ctx.fillStyle = 'white';
        ctx.fillText(text, x, y);
    }

    drawAngleArc(ctx, point1, vertex, point2, color) {
        const radius = 30;
        const angle1 = Math.atan2(point1.y - vertex.y, point1.x - vertex.x);
        const angle2 = Math.atan2(point2.y - vertex.y, point2.x - vertex.x);
        
        ctx.beginPath();
        ctx.arc(vertex.x, vertex.y, radius, angle1, angle2);
        ctx.stroke();
    }

    calculateCentroid(points) {
        let x = 0, y = 0;
        points.forEach(point => {
            x += point.x;
            y += point.y;
        });
        return {
            x: x / points.length,
            y: y / points.length
        };
    }

    getMousePos(event) {
        const rect = this.canvas.getBoundingClientRect();
        return {
            x: event.clientX - rect.left,
            y: event.clientY - rect.top
        };
    }

    // 公共方法
    clearMeasurements() {
        this.measurements = [];
        this.currentMeasurement = null;
        this.isDrawing = false;
        this.redrawMeasurements();
    }

    getMeasurements() {
        return this.measurements;
    }

    exportMeasurements() {
        const data = {
            measurements: this.measurements,
            timestamp: new Date().toISOString(),
            imageInfo: this.imageViewer.currentImageData ? {
                patientName: this.imageViewer.currentImageData.patientName,
                studyDate: this.imageViewer.currentImageData.studyDate,
                seriesDescription: this.imageViewer.currentImageData.seriesDescription
            } : null
        };
        
        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        
        const link = document.createElement('a');
        link.href = url;
        link.download = `measurements_${Date.now()}.json`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        URL.revokeObjectURL(url);
    }

    importMeasurements(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (event) => {
                try {
                    const data = JSON.parse(event.target.result);
                    this.measurements = data.measurements || [];
                    this.redrawMeasurements();
                    resolve(data);
                } catch (error) {
                    reject(new Error('无效的测量数据文件'));
                }
            };
            reader.onerror = () => reject(new Error('读取文件失败'));
            reader.readAsText(file);
        });
    }
} 